import router from './router'
import { ElMessage } from 'element-plus'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import usePermissionStore from '@/store/modules/permission'
import useSettingsStore from '@/store/modules/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // 根据token判断用户是否登录
  const hasToken = localStorage.getItem('x-okapi-token')
  const usePermission = usePermissionStore()

  if (hasToken) {
    // set page title
    to.meta.title && useSettingsStore().setTitle(to.meta.title)

    /* has token*/
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
        usePermission.generateRoutes()
      }
      next()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      if (qiankunWindow.__POWERED_BY_QIANKUN__) {
        const str = window.location.href
        const arr = str.split('#')?.[0]?.split('/')
        const indexHome = arr.indexOf('home')
        const path = arr.splice(indexHome, 2).join('/')
        window.location.href = `/${path}/#/user/login`
        ElMessage.error('登录失效，请重新登录')
        NProgress.done()
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
